﻿#
# Author : itech
# 

import threading
import time
from hashlib import md5
import subprocess

# ====================================================
# Common functions

def runCommandWithOutput(cmd,stdinstr = ''):
  p=subprocess.Popen(cmd, shell=True, universal_newlines=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  (stdoutdata, stderrdata) = p.communicate(stdinstr)
  return p.returncode, stdoutdata, stderrdata
  
def getStr(str):
  if isinstance(str,unicode):
    return str.encode('utf-8')
  return str
  
def runNewThreadAndWait(func,args):
  t = threading.Thread(target=func, args=args)
  t.start()
  while (t.isAlive()) : time.sleep(30)
  
def OpenFile(inPath):
    file = open(inPath, 'r')
    fileStr = ''
    if file:
        fileStr = file.read()
        file.close()
    return fileStr
    
def WriteFile(outPath,fileStr):
    file = open(outPath, 'w')
    if file:
        file.write(fileStr)
        file.close()
        return True
    else:
        return False
        
def calMD5ForStr(s):
  m = md5()
  m.update(s)
  return m.hexdigest()
  
def calMD5ForFile(file):
  a_file = open(file, 'rb')
  md5 = calMD5ForStr(a_file.read())
  a_file.close()
  return md5
  

  